GNBF5010 Homework 1¶
Student id: 1155228903
Question 1¶
The month of February normally has 28 days. But if it is a leap year, February has 29 days. Write a program that asks the user to enter a year (No input validation is needed).
The program should then display the number of days in February that year. Use the following criteria to identify leap years:
- Determine whether the year is divisible by 100. If it is, then it is a leap year if and only if it is also divisible by 400. For example, 2000 is a leap year, but 2100 is not.
- If the year is not divisible by 100, then it is a leap year if and only if it is divisible by 4. For example, 2008 is a leap year, but 2009 is not.
Here is a sample run of the program:
Enter a year: 2008
In 2008, February has 29 days.
def main():
year = int(input("Enter a year: "))
print("In", year, ", February has", "29 days." if detect_leap_year(year) else "28 days.")
# Check if the year is a leap year
def detect_leap_year(year):
'''
Definition: leap years are divisible by 4, except for years that are
divisible by 100 unless they are also divisible by 400.
'''
# Check if the year is divisible by 100
if year % 100 == 0:
# If it is divisible by 100, it is a leap year only if it is also divisible by 400
return year % 400 == 0
else:
# If it is not divisible by 100, it is a leap year if it is divisible by 4
return year % 4 == 0
if __name__ == "__main__":
main()
In 2000 , February has 29 days.
Question 2¶
Suppose you have a sequence string as a variable, like seq = "ACTAGATGA". Write a program that uses the seq variable to create two new variables, first_half andsecond_half that contain the first half (rounded down) and the second half (rounded up) of seq. When printed, these two should print "ACTA" and "GATGA", respectively.
Importantly, your code should work no matter what the string seq refers to. For example, if seq = "TACTTG", then your code should return first_half referring to "TAC" and second_half referring to "TTG". You may also want to validate that the length of the string is at least 2.
Your main program could look like this:
seq = "ACTAGATGA"
## Your own code here:
## …
print(first_half) # should print "ACTA"
print(second_half) # should print "GATGA"
def main():
# Define a sequence string
seq = "ACTAGATGA"
try:
first_half, second_half = divide_seq(seq)
print(first_half)
print(second_half)
except ValueError as e:
print(e)
# Take a sequence string and divides it into two halves.
def divide_seq(seq):
'''
Definition: the first half contains the first half of the characters (rounded down),
and the second half contains the remainder of the characters (rounded up).
'''
# Validate that the length of the string is at least 2, if not, then separate the sequence into two part.
if len(seq) < 2:
raise ValueError("The sequence string must be at least 2 characters long.")
else:
mid_index = len(seq) // 2
return seq[:mid_index], seq[mid_index:]
if __name__ == "__main__":
main()
ACTA GATGA
Question 3¶
Write a program that uses nested loops to draw this pattern.
Note: Pretend that string multiplications like "abc"*3 doesn’t exist.
##
# #
# #
# #
# #
# #
def main():
# Define the number of lines in the pattern
num_lines = 6
pattern = loop_tower(num_lines)
# Print each line in this pattern
for line in pattern:
print(line)
# Build the '#' tower
def loop_tower(height):
'''
Definition: ("#") + (" ") * (height - 1) + ("#")
'''
pattern = []
for i in range(1, height + 1):
line = "#" + " " * (i - 1) + "#"
pattern.append(line)
return pattern
if __name__ == "__main__":
main()
## # # # # # # # # # #
Question 4¶
Write a program that continually generates and sums up random numbers between 1 and 20 and stops when the sum exceeds 1000. Stop early with a warning message if more than 100 numbers have been generated. At the end, print the sum and the number of random integers generated. Use random.randint(1, 20)
to generate a random integer between 1 and 20 (inclusive). To start with, you may use the providedtemplate of q4. The output may look like this.
95 random number are generated; sum = 1007.
>>> Early break because 100 numbers have been generated.
101 random number are generated; sum = 993.
import random
def main():
# Define the range of these random numbers and maximum sum value, maximum quantity of it
sum_rand_nums(1, 20, 1000, 100)
# Sum the random value and output the counting of it
def sum_rand_nums(start, end, sum_limit, max_n):
'''
Definition: sums up random numbers between start and end,
finally stops when the sum > sum_limit or n > max_n.
'''
current_sum = 0
count = 0
while True:
num = random.randint(start, end)
current_sum += num
count += 1
if count >= max_n:
print(f">>> Early break because {max_n} numbers have been generated.")
break
if current_sum > sum_limit:
break
print(f"{count} random number{'s' if count != 1 else ''} are generated; sum = {current_sum}.")
if __name__ == "__main__":
main()
>>> Early break because 100 numbers have been generated. 100 random numbers are generated; sum = 904.
Question 5¶
Assume s is a string of lower-case characters (You may assign s directly in the program, no need to ask the user for input). Write a program that prints the longest substring of s in which the letters occur in alphabetical order. Print the only first occurrence if there are two or more alphabetically ordered substrings with the same length.
For example, if s = 'azcbobobegghakl'
, then your program should print
Longest substring in alphabetical order is: beggh
If s = 'abcbcd'
, then your program should print
Longest substring in alphabetical order is: ab
def main():
# Define a string with random letters
s = 'azcbobobegghakl'
longest_alphabetical_substring(s)
def longest_alphabetical_substring(s):
'''
Definition: use double pointer i and j to locate the substring of s, by compareing
the current and previous longest alphabetical substring to find the
solution.
'''
max_length = 0
start_index = 0
for i in range(len(s)):
for j in range(i+1, len(s)+1):
substring = s[i:j]
if is_alphabetical(substring) and len(substring) > max_length:
max_length = len(substring)
start_index = i
print(f"Longest substring in alphabetical order is: {s[start_index : start_index + max_length]}")
def is_alphabetical(substring):
'''
Definition: determine whether a string is alphabetical by iterating through a loop
and comparing whether the previous character is greater than the next
character
'''
for i in range(len(substring) - 1):
if substring[i] > substring[i + 1]:
return False
return True
if __name__ == "__main__":
main()
Longest substring in alphabetical order is: beggh